﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.CBO.SCM.Item;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// ItemCategoryCrossSaveSV partial 
	/// </summary>	
	public partial class ItemCategoryCrossSaveSV 
	{	
		internal BaseStrategy Select()
		{
			return new ItemCategoryCrossSaveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class ItemCategoryCrossSaveSVImpementStrategy : BaseStrategy
	{
		public ItemCategoryCrossSaveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			ItemCategoryCrossSaveSV bpObj = (ItemCategoryCrossSaveSV)obj;
			List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

            try
            {
				if (bpObj.Data == null || bpObj.Data.Count <= 0)
					throw new Exception("传入参数为空");

				foreach (var dto in bpObj.Data)
				{
					ItemCategoryCross entity = ItemCategoryCross.Finder.Find($"Item.Code='{dto.Item.Code}' and CategoryKind={dto.CategoryKind} and Org={Context.LoginOrg.ID}");
					//默认值
					dto.Org = new CopyOfCommonArchiveDataDTOData
					{
						ID = Context.LoginOrg.ID,
						Code = Context.LoginOrg.Code,
					};

					if (entity == null)
					{
						//新增逻辑
						using (ISession session = Session.Open())
						{
							entity = ItemCategoryCross.Create();
							entity.Item = EntityUtils.GetEntityByCode<ItemMaster>(dto.Item.Code);
							entity.Category = EntityUtils.getItemCategory(dto.Category.Code, dto.CategoryKind);
							entity.CategoryKind = CategoryKindEnum.GetFromValue(dto.CategoryKind);
							entity.Org = EntityUtils.GetEntityByCode<Organization>(dto.Org.Code);

							session.Commit();
						}
					}
					else
					{
						//修改逻辑
						using (ISession session = Session.Open())
						{
							entity.Category = EntityUtils.getItemCategory(dto.Category.Code,dto.CategoryKind);

							session.Commit();
						}
					}

					CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
					{
						ID = entity.ID,
						Code = entity.Item.Code,
						Name = entity.Item.Name,
					};
					retlist.Add(ret);
				}

				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
            {
				return ResultUtils.error(bpObj, bpObj.Data, ex);
            }
			
		}		
	}

	#endregion
	
	
}